<?php

namespace backend\modules\orders\controllers;

use backend\modules\base\controllers\BaseController;
use backend\modules\orders\lib\KdApiEOrderDemo;
use backend\modules\orders\models\OrderGoods;
use backend\modules\shipping\models\Shipping;
use Yii;
use backend\modules\orders\models\OrderInfo;
use backend\modules\orders\models\search\OrderInfoSearch;
use yii\base\Exception;
use yii\data\Pagination;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * OrderinfoController implements the CRUD actions for OrderInfo model.
 */
class OrderinfoController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => [ 'index','sort','create','view','update','del','shiptochange','downtoadd','showwuliu'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all OrderInfo models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new OrderInfoSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $data = OrderInfo::find()->select([
            'order_id' ,
        ])->where(['is_delete'=>0])->all();

        $pages = new Pagination(['totalCount' =>count($data), 'pageSize' => '20']);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'pages'=>$pages
        ]);
    }

    /**
     * Displays a single OrderInfo model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new OrderInfo model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new OrderInfo();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->order_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing OrderInfo model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $addec = new \backend\modules\orders\lib\AddExchange();
        $addec->exchangeObj($model);
        //选中显示页面
        $FormPage = isset($_GET['whiceForm'])?$_GET['whiceForm']:'FormPage01';

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->order_id]);
        } else {
            $orderGoods = OrderGoods::find()->where(['order_id'=>$id])->all();
            $shippingARR = OrderInfo::getShippingByOrderId($id);
            return $this->render('update', [
                'model' => $model,
                'orderGoods'=>$orderGoods,
                'shippingARR'=>$shippingARR,
                'FormPage'=>$FormPage
            ]);
        }
    }

    /**
     * Deletes an existing OrderInfo model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the OrderInfo model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return OrderInfo the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = OrderInfo::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * 处理订单物流非电子面单
     *
     * @return string|\yii\web\Response
     */
    public function actionShiptochange()
    {
        $postData = Yii::$app->request->post();
        $inoval = $postData['inoval'];
        $new_shippingid = $postData['new_shippingid'];
        $order_shippingid = $postData['order_shippingid'];
        $order_id = $postData['order_id'];

        //判断之前物流订单是否电子下单
        $Shipping = Shipping::findOne($order_shippingid);
        if($Shipping){
            if($Shipping->shipping_id=='23'){
                return json_encode([false,'该订单是电子面单下单不能修改物流！']);
            }
        }

        $shipping_name = Shipping::findOne($new_shippingid)->shipping_name;
        $beginTransaction = Yii::$app->db->beginTransaction();
        try{
            $OrderInfo = OrderInfo::find()->where(['order_id'=>$order_id])->asArray()->one();
            OrderInfo::getDeliveryGoodsM($OrderInfo);
            $num = OrderInfo::updateAll(
                [
                    'shipping_id' => $new_shippingid,
                    'shipping_name'=>$shipping_name,
                    'order_status'=>2,
                    'shipping_status'=>1,
                    'invoice_no'=>$inoval
                ],
                ['order_id' => $order_id]
            );
            if($num){
                $beginTransaction->commit();
                return $this->redirect(['update','id'=>$order_id,'whiceForm'=>'FormPage02']);
            } else {
                $beginTransaction->rollBack();
                return json_encode([false,'物流修改错误']);
            }
        }catch (Exception $e) {
            $beginTransaction->rollBack();
            return json_encode([false,$e->getMessage()]);
        }

    }

    /**
     * 电子面单下单
     *
     * @return string|\yii\web\Response
     */
    public function actionDowntoadd()
    {
        $postData = Yii::$app->request->post();
        $new_shippingid = $postData['new_shippingid'];
        $order_shippingid = $postData['order_shippingid'];
        $order_id = $postData['order_id'];

        $OrderInfo = OrderInfo::find()->where(['order_id'=>$order_id])->asArray()->one();

        if($OrderInfo['shipping_id']){
            return json_encode([false,'该订单是电子面单下单不能修改物流！']);
        }

        $addEX = new \backend\modules\orders\lib\AddExchange();
        $OrderInfo = $addEX->exchangeArr($OrderInfo);

        $kad = new KdApiEOrderDemo();
        $result = $kad->setTempInfoShip($OrderInfo);
        if($result['ResultCode']==100){
            $beginTransaction = Yii::$app->db->beginTransaction();
            $shipping_name = Shipping::findOne($new_shippingid)->shipping_name;
            try{
                OrderInfo::getDeliveryGoodsM($OrderInfo);
                $num = OrderInfo::updateAll(
                    [
                        'shipping_id' => $new_shippingid,
                        'shipping_name'=>$shipping_name,
                        'invoice_no'=>$result['Order']['LogisticCode'],
                        'order_status'=>2,
                        'shipping_status'=>1,
                        'shopping_temp'=>$result['PrintTemplate']
                    ],
                    ['order_id' => $order_id]
                );
                if($num) {
                    $beginTransaction->commit();
                    return $this->redirect(['update','id'=>$order_id,'whiceForm'=>'FormPage02']);
                }  else {
                    $beginTransaction->rollBack();
                    return json_encode([false,'修改数据错误']);
                }
            } catch (Exception $e) {
                $beginTransaction->rollBack();
                return json_encode([false,$e->getMessage()]);
            }

        } else {
            return json_encode([false,'电子面单下单失败，返回码：'.$result['ResultCode']]);
        }

    }

    public function actionShowwuliu()
    {
        $post = Yii::$app->request->post();
        $orderInfo = OrderInfo::findOne($post['order_id']);
        $invoice_no = $orderInfo->invoice_no;
        $shipping_code = Shipping::findOne($orderInfo->shipping_id)->shipping_code;
        $wuliuApi = new \backend\modules\orders\lib\WuliuApi();
        $arrJson = $wuliuApi->getOrderTracesByJson($shipping_code,$invoice_no);
        return "[true,$arrJson]";
    }

}
